package com.crazymaker.demo.proxy.basic;

import com.alibaba.fastjson.JSONObject;
import com.crazymaker.springcloud.common.result.RestOut;
import com.crazymaker.springcloud.seckill.remote.client.DemoClient;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

@Slf4j
public class StaticProxyTester
{

    /**
     * 静态代理测试
     */
    @Test
    public void staticProxyTest()
    {
        DemoClient client = new DemoClientImpl();
        DemoClient proxy = new DemoClientProxy(client);

        RestOut<JSONObject> result1 = proxy.hello();
        log.info("result1={}", result1.toString());

        RestOut<JSONObject> result2 = proxy.echo("回显内容" );
        log.info("result2={}", result2.toString());
    }

    /**
     * 动态代理测试
     */
    @Test
    public void dynamicProxyTest()
    {
        DemoClient client = new DemoClientImpl();
        //参数1：类装载器
        ClassLoader classLoader = StaticProxyTester.class.getClassLoader();
        //参数2：被代理的实例类型
        Class[] clazz = new Class[]{DemoClient.class};
        //参数3：调用处理器
        InvocationHandler invocationHandler = new DemoClientInocationHandler(client);
        DemoClient proxy = (DemoClient)
                Proxy.newProxyInstance(classLoader, clazz, invocationHandler);
        RestOut<JSONObject> result1 = proxy.hello();
        log.info("result1={}", result1.toString());
        RestOut<JSONObject> result2 = proxy.echo("回显内容" );
        log.info("result2={}", result2.toString());
    }


}
